package model

import (
	"errors"
	"gorm.io/gorm"
)

type (
	GateRuleMode struct {
		db *gorm.DB
	}

	GateRule struct {
		Model
		ThingId    string `gorm:"varchar(40);not null;index" json:"thing_id"`
		UserId     int64  `gorm:"index;not null" json:"user_id"`
		IsCard     bool   `json:"is_card"` // 工卡
		CardId     string `gorm:"default:'';type:varchar(64)" json:"card_id"`
		IsFinger   bool   `json:"is_fingerprint"` // 指纹
		FingerId   string `gorm:"default:'';type:varchar(64)" json:"finger_id"`
		IsFace     bool   `json:"is_face"` // 人脸
		FaceImg    string `gorm:"default:'';type:varchar(64)" json:"face_img"`
		IsBackList bool   `json:"is_back_list"`
		StartTime  int    `gorm:"default:0" json:"start_time"` // 开始时间
		EndTime    int    `gorm:"default:0" json:"end_time"`   // 结束时间
		GType      int    `gorm:"default:1" json:"g_type"`     // 门禁的类型 1、员工 2、访客  3、黑名单  *必填项
	}
)

func NewGateRule(db *gorm.DB) *GateRuleMode {
	return &GateRuleMode{
		db: db,
	}
}

func (m *GateRuleMode) Create(data *GateRule) error {
	return m.db.Create(data).Error
}

func (m *GateRuleMode) Delete(id int64) error {
	return m.db.Where("id = ?", id).Delete(&GateRule{}).Error
}

func (m *GateRuleMode) FindByUserId(userId int64) ([]GateRule, error) {
	var list []GateRule
	err := m.db.Model(&GateRule{}).Where("user_id = ?", userId).Find(&list).Order("id desc").Limit(100).Error
	if errors.Is(gorm.ErrRecordNotFound, err) {
		return []GateRule{}, nil
	}
	//todo 切断list，防止内存逃逸，但是有一定的代价
	return append([]GateRule{}, list...), err
}

func (m *GateRuleMode) Update(rule GateRule) (int64, error) {
	resp := m.db.Where("id = ?", rule.ID).Updates(rule)
	return resp.RowsAffected, resp.Error
}
func (m *GateRuleMode) QueryWhereMap(data map[string]interface{}) (GateRule, error) {
	var resp GateRule
	err := m.db.Model(&GateRule{}).Where(data).First(&resp).Error
	return resp, err
}

func (m *GateRuleMode) QueryWhereMapCount(data map[string]interface{}) (int64, error) {
	var total int64
	err := m.db.Model(&GateRule{}).Where(data).Count(&total).Error
	return total, err
}

func (m *GateRuleMode) QueryWhereMapList(data map[string]interface{}, page int, size int) ([]GateRule, error) {
	var list []GateRule
	err := m.db.Model(&GateRule{}).Where(data).Limit(size).Offset((page - 1) * size).Find(&list).Order("id desc").Limit(100).Error
	if errors.Is(gorm.ErrRecordNotFound, err) {
		return []GateRule{}, nil
	}
	//todo 切断list，防止内存逃逸，但是有一定的代价
	return append([]GateRule{}, list...), err
}
